package cn.smile.utils;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author 10834
 */
@SuppressWarnings("NullableProblems")
@Component
public class SpringContextUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }

    /**
     * 获取HttpServletRequest
     */
    public static HttpServletRequest getHttpServletRequest() {
        if (ObjectUtils.isEmpty(RequestContextHolder.getRequestAttributes())) {
            return null;
        }
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获取项目根路径 basePath
     */
    public static String getDomain() {
        HttpServletRequest request = getHttpServletRequest();
        if (ObjectUtils.isEmpty(request)) {
            return null;
        }
        StringBuffer url = request.getRequestURL();

        return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
    }

    @SuppressWarnings("unused")
    public static Object getAppCon(String beanName) {
        return applicationContext.getBean(beanName);
    }
}
